﻿#include "GLLInc.h"

#ifdef GLL_WIN

namespace GLL
{
	uint String::char_num() const
	{
		return MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)c_str_utf8(), -1, 0, 0) - 1;
	}

	//-----------------------------------------
	//最多512个字
	const static int Max_UCS2_len = 512; //wchar_t  2 byte
	const static int Max_UTF8_len = Max_UCS2_len * 3;//utf8 每个汉字 3 byte
	const static int Max_CP_len = Max_UCS2_len * 2;//计算机相应code page 每个汉字 2 byte

	static wchar_t strUCS2[Max_UCS2_len + 1] = {0};
	static char strUtf8[Max_UTF8_len + 1] = {0};
	static char strCP[Max_CP_len + 1] = {0};
	int arg_str_len_out;

	String Str2Utf8(const String& strStr, int& length_out)
	{
		length_out = 0;
		if(strStr.empty()) return String();
		const char* str = strStr.c_str();
		int str_len = strStr.length();

		int actual_UCS2_len = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)str, str_len, strUCS2, Max_UCS2_len);
		strUCS2[actual_UCS2_len] = 0;//保证str_len以后0结束
		int actual_UTF8_len = WideCharToMultiByte (CP_UTF8, 0, strUCS2, actual_UCS2_len, strUtf8, Max_UTF8_len, NULL,NULL);
		strUtf8[actual_UTF8_len] = 0;

		length_out = actual_UTF8_len;
		return String((utf8*)strUtf8);
	}

	String Utf82Str(const String& str, int& length_out)
	{
		length_out = 0;
		if(str.empty()) return String();
		const utf8* strUtf8 = str.c_str_utf8();
		int str_len = str.length();

		int actual_UCS2_len = MultiByteToWideChar(CP_UTF8, 0, (char*)strUtf8, str_len, strUCS2, Max_UCS2_len);
		strUCS2[actual_UCS2_len] = 0;//保证str_len以后0结束
		int actual_CP_len = WideCharToMultiByte (CP_ACP, 0, strUCS2, actual_UCS2_len, strCP, Max_CP_len, NULL,NULL);
		strCP[actual_CP_len] = 0;

		length_out = actual_CP_len;
		return String(strCP);
	}

};//GLL

#endif GLL_WIN
